import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;

/**
 * Created by haiqiang on 17/5/20.
 */
public class demoJsonPath {
    final static String json = "{\n" +
            "    \"tool\": \n" +
            "    {\n" +
            "        \"jsonpath\": \n" +
            "        {\n" +
            "            \"creator\": \n" +
            "            {\n" +
            "                \"name\": \"Jayway Inc.\",\n" +
            "                \"location\": \n" +
            "                [\n" +
            "                    \"Malmo\",\n" +
            "                    \"San Francisco\",\n" +
            "                    \"Helsingborg\"\n" +
            "                ]\n" +
            "            }\n" +
            "        }\n" +
            "    },\n" +
            " \n" +
            "    \"book\": \n" +
            "    [\n" +
            "        {\n" +
            "            \"title\": \"Beginning JSON\",\n" +
            "            \"price\": 49.99\n" +
            "        },\n" +
            " \n" +
            "        {\n" +
            "            \"title\": \"JSON at Work\",\n" +
            "            \"price\": 29.99\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    public static void main(String[] args) {
        String jsonPathCreatorNamePath = "$['tool']['jsonpath']['creator']['name']";
        String jsonPathCreatorLocationPath = "$['tool']['jsonpath']['creator']['location']";

        DocumentContext jsonContext = JsonPath.parse(json);
        String jsonPathCreatorName = jsonContext.read(jsonPathCreatorNamePath);
        List<String> jsonPathCreatorLocation = jsonContext.read(jsonPathCreatorLocationPath);

        assertEquals("Jayway Inc.", jsonPathCreatorName);
        assertThat(jsonPathCreatorLocation.toString(), containsString("Malmo"));
        assertThat(jsonPathCreatorLocation.toString(), containsString("San Francisco"));
        assertThat(jsonPathCreatorLocation.toString(), containsString("Helsingborg"));
    }
}
